﻿using System;
using System.Web.Mvc;
using Autofac;
using Zinnia.Common.IOC;
using Zinnia.Core.Web.MVC.ViewModels;

namespace Zinnia.Core.Web.MVC.Controller
{
    /// <summary>
    /// 表单控制器 业务逻辑请求处理管道模型
    /// </summary>
    public class FormController : BaseController
    {
        public virtual ILifetimeScope Scope { get; set; }
        /// <summary>
        /// 处理表单逻辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [NonAction]
        public ActionResult Form(ActionForm model)
        {
            try
            {
                Init(model);
                return View(model);
            }
            catch (Exception ex)
            {
                return ExceptionImp(model, ex);
            }
        }
        [NonAction]
        public ActionResult JsonFrom(ActionForm model)
        {
            try
            {
                Init(model);
                return Json(model);
            }
            catch (Exception ex)
            {
                return ExceptionImp(model, ex);
            }
        }
        [NonAction]
        public ActionResult JsonFrom(ActionForm model, JsonRequestBehavior behavior)
        {
            try
            {
                Init(model);
                return Json(model, behavior);
            }
            catch (Exception ex)
            {
                return ExceptionImp(model, ex);
            }
        }

        private void Init(ActionForm model)
        {
            model.OnRequestFormExecuted();
            //模型注入
            Scope.Setup(model);
            model.OnRequestFormExecuting();
            model.OnResultExecuted();
            model.OnResultExecuting();
        }

        /// <summary>
        /// 默认抛出异常,处理捕捉到的异常
        /// </summary>
        /// <param name="model"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        [NonAction]
        public virtual ActionResult ExceptionImp(ActionForm model, Exception ex)
        {
            //To Do 记录日志
            throw ex;
        }
        /// <summary>
        /// 当前接口不满足需求时，扩展该接口重写方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual ActionResult ActionFromReset(ActionForm model)
        {
            return model.ActionFromReset();
        }
    }
}
